<?php

namespace app\admin\controller;

use think\Db;

/**
 * 仪表盘管理控制器
 */
class Dashboard extends Base
{
    /**
     * 获取统计数据
     */
    public function getStatistics()
    {
        try {
            // 症状分类统计
            $categories = Db::name('symptom_categories')->count();

            // 症状统计
            $symptoms = Db::name('symptoms')->count();
            $activeSymptoms = Db::name('symptoms')->where('is_active', 1)->count();

            // 汤药统计
            $formulas = Db::name('formulas')->count();
            $activeFormulas = Db::name('formulas')->where('is_active', 1)->count();

            // 有主症状的汤药数量
            $formulasWithMainSymptoms = Db::name('formulas')
                ->where('main_symptom_ids', '<>', '')
                ->whereNotNull('main_symptom_ids')
                ->count();

            // 有兼症状的汤药数量
            $formulasWithSideSymptoms = Db::name('formulas')
                ->where('side_symptom_ids', '<>', '')
                ->whereNotNull('side_symptom_ids')
                ->count();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'categories' => $categories,
                    'symptoms' => $symptoms,
                    'activeSymptoms' => $activeSymptoms,
                    'formulas' => $formulas,
                    'activeFormulas' => $activeFormulas,
                    'formulasWithMainSymptoms' => $formulasWithMainSymptoms,
                    'formulasWithSideSymptoms' => $formulasWithSideSymptoms
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取统计数据失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取最近添加的症状
     */
    public function getRecentSymptoms()
    {
        try {
            $limit = input('limit', 5);

            $symptoms = Db::name('symptoms')
                ->alias('s')
                ->join('symptom_categories sc', 's.category_id = sc.id')
                ->field('s.id,s.name_zh_cn,s.name_en_us,s.name_ja_jp,s.name_be_by,s.created_at,sc.name_zh_cn as category_name_zh_cn,sc.name_en_us as category_name_en_us,sc.name_ja_jp as category_name_ja_jp,sc.name_be_by as category_name_be_by')
                ->order('s.created_at desc')
                ->limit($limit)
                ->select();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $symptoms
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取最近症状失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取最近添加的汤药
     */
    public function getRecentFormulas()
    {
        try {
            $limit = input('limit', 5);

            $formulas = Db::name('formulas')
                ->field('id,name_zh_cn,name_en_us,name_ja_jp,name_be_by,is_active,created_at')
                ->order('created_at desc')
                ->limit($limit)
                ->select();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $formulas
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取最近汤药失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取综合概览数据
     */
    public function getOverview()
    {
        try {
            // 获取统计数据
            $statisticsResponse = $this->getStatistics();
            $statisticsData = json_decode($statisticsResponse->getContent(), true);

            // 获取最近症状数据
            $symptomsResponse = $this->getRecentSymptoms();
            $symptomsData = json_decode($symptomsResponse->getContent(), true);

            // 获取最近汤药数据
            $formulasResponse = $this->getRecentFormulas();
            $formulasData = json_decode($formulasResponse->getContent(), true);

            if ($statisticsData['code'] === 0 && $symptomsData['code'] === 0 && $formulasData['code'] === 0) {
                return json([
                    'code' => 0,
                    'msg' => 'success',
                    'data' => [
                        'statistics' => $statisticsData['data'],
                        'recentSymptoms' => $symptomsData['data'],
                        'recentFormulas' => $formulasData['data']
                    ]
                ]);
            } else {
                return json([
                    'code' => 1,
                    'msg' => '获取概览数据失败'
                ]);
            }
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取概览数据失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取系统健康状态
     */
    public function getSystemHealth()
    {
        try {
            // 检查数据完整性
            $formulasWithoutSymptoms = Db::name('formulas')
                ->where(function($query) {
                    $query->where('main_symptom_ids', '')
                          ->whereOr('main_symptom_ids', null);
                })
                ->where(function($query) {
                    $query->where('side_symptom_ids', '')
                          ->whereOr('side_symptom_ids', null);
                })
                ->count();

            $symptomsWithoutCategory = Db::name('symptoms')
                ->where('category_id', 0)
                ->whereOr('category_id', null)
                ->count();

            $inactiveFormulas = Db::name('formulas')
                ->where('is_active', 0)
                ->count();

            $inactiveSymptoms = Db::name('symptoms')
                ->where('is_active', 0)
                ->count();

            // 计算健康评分
            $totalFormulas = Db::name('formulas')->count();
            $totalSymptoms = Db::name('symptoms')->count();

            $healthScore = 100;
            if ($totalFormulas > 0) {
                $healthScore -= ($formulasWithoutSymptoms / $totalFormulas) * 30; // 无症状汤药扣30分
                $healthScore -= ($inactiveFormulas / $totalFormulas) * 10; // 禁用汤药扣10分
            }
            if ($totalSymptoms > 0) {
                $healthScore -= ($symptomsWithoutCategory / $totalSymptoms) * 20; // 无分类症状扣20分
                $healthScore -= ($inactiveSymptoms / $totalSymptoms) * 5; // 禁用症状扣5分
            }

            $healthScore = max(0, min(100, round($healthScore)));

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'healthScore' => $healthScore,
                    'issues' => [
                        'formulasWithoutSymptoms' => $formulasWithoutSymptoms,
                        'symptomsWithoutCategory' => $symptomsWithoutCategory,
                        'inactiveFormulas' => $inactiveFormulas,
                        'inactiveSymptoms' => $inactiveSymptoms
                    ],
                    'suggestions' => $this->getHealthSuggestions($formulasWithoutSymptoms, $symptomsWithoutCategory, $inactiveFormulas, $inactiveSymptoms)
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取系统健康状态失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取健康建议
     */
    private function getHealthSuggestions($formulasWithoutSymptoms, $symptomsWithoutCategory, $inactiveFormulas, $inactiveSymptoms)
    {
        $suggestions = [];

        if ($formulasWithoutSymptoms > 0) {
            $suggestions[] = "有 {$formulasWithoutSymptoms} 个汤药没有配置症状，建议为其添加主症状或兼症状";
        }

        if ($symptomsWithoutCategory > 0) {
            $suggestions[] = "有 {$symptomsWithoutCategory} 个症状没有分类，建议为其指定症状分类";
        }

        if ($inactiveFormulas > 0) {
            $suggestions[] = "有 {$inactiveFormulas} 个汤药被禁用，请检查是否需要启用";
        }

        if ($inactiveSymptoms > 0) {
            $suggestions[] = "有 {$inactiveSymptoms} 个症状被禁用，请检查是否需要启用";
        }

        if (empty($suggestions)) {
            $suggestions[] = "系统数据完整，运行状态良好";
        }

        return $suggestions;
    }
}